#!/usr/bin/env python
# encoding: utf-8

import time
from django.shortcuts import render, redirect,reverse
from django.http import JsonResponse, HttpResponse
from django.contrib.auth.decorators import login_required, user_passes_test

from app01.forms.project import ProjectModelForm
from app01 import models


@login_required
def project_list(request):
	
	"""项目列表"""
	if request.method == "GET":
		# GET请求查看项目列表
		"""
		1. 从数据库中获取两部分数据
			我创建的所有项目：已星标、未星标
			我参与的所有项目：已星标、未星标
		2. 提前已星标
			循环 = 循环[我创建的所有项目] + [我参与的所有项目] 吧已星标的数据提取
			
		得到三个列表：星标、创建、参与
		"""
		project_dict = {'star': [], 'my': [], 'join': []}
		my_project_list = models.Project.objects.filter(creator=request.tracer.user)
		for row in my_project_list:
			if row.star:
				project_dict['star'].append({"value": row, "type": "my"})
			else:
				project_dict['my'].append(row)

		join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
		for item in join_project_list:
			if item.star:
				project_dict['star'].append({"value": item.project, "type": "join"})
			else:
				project_dict['join'].append(item.project)

		form = ProjectModelForm(request)

		return render(request, 'project_list.html', {'form': form,'project_dict': project_dict})

	# POST，对话框的ajax添加项目。
	form = ProjectModelForm(request, data=request.POST)
	if form.is_valid():
		# 1. 为项目创建一个桶
		# name = form.cleaned_data.get('name')
		# bucket = "{}-{}-1302428193".format(request.tracer.user.phone, str(int(time.time())))
		# region = "ap-chengdu"
		# create_bucket(bucket=bucket, region=region)

		# 把桶和区域写入数据库

		# 验证通过: 项目名、颜色、描述 + creator谁创建的项目
		# form.instance.bucket = bucket
		# form.instance.region = region
		form.instance.creator = request.tracer.user
		# 创建项目
		instance = form.save()

		# 3 项目初始化项目类型
		issue_type_object_list = []
		for item in models.IssuesType.PROJECT_INIT_LIST:
			issue_type_object_list.append(models.IssuesType(project=instance, title=item))
		models.IssuesType.objects.bulk_create(issue_type_object_list)

		return JsonResponse({'status': True})

	# 验证不通过 返回错误信息
	return JsonResponse({'status': False, 'error': form.errors})


def project_star(request, project_type, project_id):
	"""星标项目"""
	if project_type == "my":
		models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
		return redirect('project_list')

	elif project_type == "join":
		models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
		return redirect('project_list')

	return HttpResponse('请求错误')


def project_unstar(request, project_type, project_id):
	"""取消星标"""
	if project_type == "my":
		models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
		return redirect('project_list')

	elif project_type == "join":
		models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
		return redirect('project_list')

	return HttpResponse('请求错误')


def all_wiki(request):
	wikis=models.Wiki.objects.all().order_by('-create_datetime')
	if request.method=='GET':
		return render(request, 'all_project_wiki_list.html', {'wikis': wikis})


from django.utils.dateparse import parse_datetime

import json
def search_wiki(request):
	if request.method == 'GET':
		project_list=models.Project.objects.values_list('name',flat=True).distinct()
		product_list=models.Product.objects.values_list('name',flat=True).distinct()
		station_list=models.Station.objects.values_list('name',flat=True).distinct()
		belong_to_list=models.Group.objects.all()
		user_list=models.User.objects.all()
		station_cato_list=models.Station._meta.get_field('catogory').choices

		content={
			'project_list':project_list,
			'product_list':product_list,
			'station_list':station_list,
			'belong_to_list':belong_to_list,
			'user_list':user_list,
			'station_cato_list':station_cato_list,
		}

		return render(request, 'search_wiki.html',content)
	
	if request.method == 'POST':
		# 获取请求体中的 JSON 数据
		data = request.body.decode('utf-8')
		data = json.loads(data)
		start_time = data.get('start_time')
		print('start_time:',start_time)

		 # 检查 start_time 是否为空
		if not start_time:
			return JsonResponse({'status': False, 'error': 'start_time is required'}, status=400)
		
		# 确保 start_time 是字符串
		if not isinstance(start_time, str):
			return JsonResponse({'status': False, 'error': 'start_time must be a string'}, status=400)
		
		# 解析 start_time
		start_datetime = parse_datetime(start_time)
		if not start_datetime:
			return JsonResponse({'status': False, 'error': 'Invalid start_time format'}, status=400)
	
		# 获取到wiki中create_datetime大于等于start_time的 queryset,
		wiki_list = models.Wiki.objects.filter(create_datetime__gte=parse_datetime(start_time)).order_by('-create_datetime')
		# 将 queryset 转换为 JSON 可序列化的格式
		wiki_list_serialized = [
			{
				'id': wiki.id,
				'project': {'name': wiki.project.name,'id': wiki.project.id},
				'product': {'name': wiki.product.name},
				'station': {
					'name': wiki.Station.name,
					'belong_to': {'name': wiki.Station.belong_to.name},
					'catogory_display': wiki.Station.get_catogory_display(),
					'equip_no': wiki.Station.equip_no
				},
				'title': wiki.title,
				'priority': wiki.priority,
				'deal_time': wiki.deal_time,
				'deal_person': {'username': wiki.deal_person.username},
				'create_datetime': wiki.create_datetime.strftime('%Y-%m-%d'),
				'url':reverse('wiki', kwargs={'project_id': wiki.project.id})+f'?wiki_id={wiki.id}'
			}
			for wiki in wiki_list
		]


		return JsonResponse({'status': True, 'wiki_list': wiki_list_serialized})